package cn.itrip.trade.config;


import cn.itrip.beans.dtos.ResultCodeEnum;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.servlet.ServletException;
import java.util.Date;

/**
 * @Author:小伟
 * @Description:
 * @Date:2019-12-28 10:16
 **/
public class JwtUtil {
    /**
     *  私钥uuid
     */
    static final String base64EncodedSecretKey = "2138a0c2-7205-4162-a3c6-d50305374792";

    /** 设置用户登录的有效时间，默认为2个小时 */
    static final long TOKEN_EXP = 7200000;

    public static String getToken(String userName) {
        return Jwts.builder()
                .setSubject(userName)
                .claim("roles", "admin")
                .setIssuedAt(new Date())
                // 过期时间
                .setExpiration(new Date(System.currentTimeMillis() + TOKEN_EXP))
                .signWith(SignatureAlgorithm.HS256, base64EncodedSecretKey)
                .compact();
    }
    /** * 检查token,只要不正确就会抛出异常 * */
    public static Claims checkToken(String token) throws ServletException {
        try {
            final Claims claims = Jwts.parser().setSigningKey(base64EncodedSecretKey).parseClaimsJws(token).getBody();
            return claims;
        } catch (ExpiredJwtException e1) {
            e1.printStackTrace();
            throw new StateException(ResultCodeEnum.USERLOGIN_INVALID_ERROR);
        } catch (Exception e) {
            e.printStackTrace();
            throw new StateException(ResultCodeEnum.USERUNLOGIN_ERROR);
        }
    }
}